load("volcano.RData") # 加载数据，假设得到名为 prostat 的数据框

library(ggplot2)

#定义阈值
p_value_threshold <- 0.05
fold_change_threshold <- 1.2
# 计算 log2倍数变化阈值
log2fc_threshold <- log2(fold_change_threshold) # log2(1.2)

# 根据 P 值和 log2 Fold Change (FC 列) 进行判断
Group <- ifelse(
  prostat$P < p_value_threshold & prostat$FC > log2fc_threshold,
  "Up", # 条件1: P < 0.05 且 log2FC > log2(1.2) -> 上调
  ifelse(
    prostat$P < p_value_threshold & prostat$FC < -log2fc_threshold,
    "Down", # 条件2: P < 0.05 且 log2FC < -log2(1.2) -> 下调
    "NotSignifi" # 其他情况 -> 不显著
  )
)
# 将 Group 转换为因子类型，方便 ggplot 控制图例顺序等
Group <- factor(Group, levels = c("Up", "Down", "NotSignifi"))


p_volcano <- ggplot(prostat, aes(x = FC, y = -log10(P), colour = Group)) +
  geom_point(alpha = 0.6, size = 1.5) + # 使用透明度和调整点大小
  scale_color_manual(values = c("Up" = "red",        # 上调为红色
                                "Down" = "blue",      # 下调为蓝色
                                "NotSignifi" = "grey")) + # 不显著为灰色
  labs(title = "Volcano Plot",
       x = "log2 Fold Change",
       y = "-log10 P-value") +
  theme_bw(base_size = 14) + # 使用黑白主题并设置基础字体大小
  theme(legend.title = element_blank()) + # 移除图例标题
  # 添加阈值参考线
  geom_vline(xintercept = c(-log2fc_threshold, log2fc_threshold),
             linetype = "dashed", color = "grey50") +
  geom_hline(yintercept = -log10(p_value_threshold),
             linetype = "dashed", color = "grey50")


# 使用 ggsave 保存为 JPG
ggsave( "volcano_plot.jpg",
       plot = p_volcano,
       device = "jpeg",  # 指定为 jpeg
       width = 8,        # 宽度
       height = 6,       # 高度
       units = "in",     # 单位
")
